<?php
/**
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */
namespace app\mobile\controller;

use app\admin\model\FigureAvatar;
use app\BaseController;
use app\common\service\AgentApiService;
use think\App;
use think\facade\Request;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use app\admin\model\FigureUser;
use app\admin\model\FigureVideo;
use app\admin\model\FigureCompositeAvatar;
use app\admin\model\FigureCompositeBackground;
use app\admin\model\FigureCompositeSound;
use app\common\service\ApiService;
use app\admin\model\FigureCloneSet;

/**
 * 视频剪辑操作
 *
 * @author Administrator
 *        
 */
class Composite extends BaseController
{

    /**
     * 声音新增
     * http://aigc.weijuyunke.cn/mobile/composite/soundAdd
     *
     * @param
     *            uid 用户id
     * @param
     *            name 名称
     * @param
     *            url 链接
     */
    public function soundAdd()
    {
        try {
            
            $uid = input('uid');
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            if (empty(input('name')))
                return result(- 1, 'name不能为空');
            if (empty(input('url')))
                return result(- 1, 'url不能为空');
            
            $soundData = array(
                'uid' => $uid,
                'name' => input('name'),
                'url' => input('url')
            );
            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }

            $result = $apiService->compositeSoundAdd([
                'name' => input('name'),
                'url' => input('url')
            ]);
            
            if (isset($result['code']) && $result['code'] == 1) {
                
                $sound = new FigureCompositeSound();
                $sound->save($soundData);
                
                $sound->save([
                    '_id' => $result['data']['id']
                ]);
                
                return result(0, '新增成功', $sound['id']);
            } else {
                return result(- 1, $result['msg']);
            }
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 形象新增
     * http://aigc.weijuyunke.cn/mobile/composite/avatarAdd
     *
     * @param
     *            uid 用户id
     * @param
     *            name 名称
     * @param
     *            url 链接
     * @param
     *            back_size 比例：1竖2横
     */
    public function avatarAdd()
    {
        try {
            
            $uid = input('uid');
            $is_avatar = input('is_avatar');
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            if (empty(input('url')))
                return result(- 1, 'url不能为空');
            
            if (! $user['is_member']) {
                $tally = sysconfig('tally', 'avatar_deduct');
                
                if ($user['balance'] < $tally) {
                    return result(- 2, '点数不足，请充值');
                }
            }
            
            $log_no = getPayNo('CT');
            
            $name = ! empty(input('name')) ? input('name') : date('YmdHis') . rand(999, 9999);
            
            $avatarData = array(
                'log_no' => $log_no,
                'uid' => $uid,
                'name' => $name,
                'url' => input('url'),
                'is_status' => 1,
                'is_avatar' => $is_avatar
            );
            
            if (! empty(input('back_size'))) {
                $avatarData['back_size'] = input('back_size');
            }
            
            $set = FigureCloneSet::where("id", 1)->find();
            if ($is_avatar &&  $is_avatar == 1  ){
                 if (sysconfig('account', 'operation_version') == 2) {
                    $apiService = new AgentApiService();
                } else {
                    $apiService = new ApiService();
                }
                $result = $apiService->compositeAvatarAdd($avatarData);


                if (isset($result['code']) && $result['code'] == 1) {

                    $avatar = new FigureCompositeAvatar();
                    $avatar->save($avatarData);

                    user_balance_used($uid, $log_no, 2, 4);

                    $avatar->save([
                        'is_status' => 2,
                        '_id' => $result['data']['id'],
                        'current_status' => 'completed'
                    ]);

                    return result(0, '新增成功', $avatar);
                }else{
                    return result(-1,  $result['msg']);
                }
            }else{
                if (isset($set['avatar_check']) && $set['avatar_check'] == 1) {

                    $avatar = new FigureCompositeAvatar();
                    $avatar->save($avatarData);

                    user_balance_used($uid, $log_no, 2, 4);

                    $avatar->save([
                        'is_status' => 1,
                        'current_status' => 'sent'
                    ]);
                    return result(0, '上传成功，等待审核',$avatar);
                } else {

                    if (sysconfig('account', 'operation_version') == 2) {
                        $apiService = new AgentApiService();
                    } else {
                        $apiService = new ApiService();
                    }

                    $result = $apiService->compositeAvatarAdd($avatarData);

                    if (isset($result['code']) && $result['code'] == 1) {

                        $avatar = new FigureCompositeAvatar();
                        $avatar->save($avatarData);

                        user_balance_used($uid, $log_no, 2, 4);

                        $avatar->save([
                            'is_status' => 2,
                            '_id' => $result['data']['id'],
                            'current_status' => 'completed'
                        ]);

                        return result(0, '新增成功', $avatar);
                    } else {

                        return result(- 1, $result['msg']);
                    }
                }
            }


        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 形象列表
     * http://aigc.weijuyunke.cn/mobile/composite/avatarList
     *
     * @param
     *            uid 用户id
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function avatarList()
    {
        try {
            $uid = input('uid');
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));
            
            $where = " uid = {$uid}   ";
            
            if (! empty(input('current_status'))) {
                $current_status = input('current_status');
                $where .= " AND current_status = '{$current_status}'";
            }
            if (!empty(input('buy_expire'))) {
                $buy_expire = input('buy_expire');

                if ($buy_expire == '2') {
                    $where .= " AND (effective_time = '0' OR effective_time > ".time().") ";
                }
            }

            $total = FigureCompositeAvatar::where($where)->count();
            if ($total) {
                $list = FigureCompositeAvatar::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
                foreach ($list as $key => $value) {

                    if ($value['effective_time']) {
                        if ( $value['effective_time']< time()){
                            $list[$key]['buy_expire'] = '1';
                            $list[$key]['buy_expire_name'] = '已过期';
                        }else{
                            $list[$key]['buy_expire'] = '2';
                            $list[$key]['buy_expire_name'] = '未过期';
                        }
                        $list[$key]['effective_time'] = date('Y-m-d ',$value['effective_time']);
                    }else{
                        $list[$key]['buy_expire'] = '2';
                        $list[$key]['buy_expire_name'] = '永久';
                    }
                }
            } else {
                $list = array();
            }
            
            $totalPage = ceil($total / $psize);
            
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 背景新增
     * http://aigc.weijuyunke.cn/mobile/composite/backgroundAdd
     *
     * @param
     *            uid 用户id
     * @param
     *            type 1-图片 2-视频
     * @param
     *            url 链接
     * @param
     *            cover_image 封面链接
     * @param
     *            back_size 视频比例：1竖2横
     */
    public function backgroundAdd()
    {
        try {
            
            $uid = input('uid');
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            $url = input('url');
            if (empty($url)) {
                return result(- 1, 'url必传');
            }
            
            $backData = array(
                'uid' => $uid,
                'type' => input('type'),
                'url' => input('url'),
                'cover_image' => input('cover_image'),
                'back_size' => input('back_size')
            );
            
            $background = new FigureCompositeBackground();
            $background->save($backData);
            
            $apiService = new ApiService();
            $result = $apiService->compositeBackgroundAdd([
                'type' => $backData['type'],
                'url' => $backData['url'],
                'cover_image' => $backData['cover_image'],
                'back_size' => $backData['back_size']
            ]);
            
            if (isset($result['code']) && $result['code'] == 1) {
                
                $background->save([
                    '_id' => $result['data']['id']
                ]);
                
                return result(0, '新增成功', $background['id']);
            } else {
                return result(- 1, $result['msg']);
            }
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 背景列表
     * http://aigc.weijuyunke.cn/mobile/composite/backgroundList
     *
     * @param
     *            uid 用户id
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function backgroundList()
    {
        try {
            $uid = input('uid');
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));
            
            $where = " uid = {$uid} ";
            
            $total = FigureCompositeBackground::where($where)->count();
            if ($total) {
                $list = FigureCompositeBackground::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
            } else {
                $list = array();
            }
            
            $totalPage = ceil($total / $psize);
            
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 背景删除
     * http://aigc.weijuyunke.cn/mobile/composite/backgroundDel
     *
     * @param
     *            uid 用户id
     * @param
     *            background_id 背景id
     */
    public function backgroundDel()
    {
        try {
            $uid = input('uid');
            $background_id = input('background_id');
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            $background = FigureCompositeBackground::where([
                'uid' => $uid,
                'id' => $background_id
            ])->find();
            if (empty($background)) {
                return result(- 1, '背景不存在');
            }
            
            $background->delete();
            
            return result(0, '删除成功');
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 形象删除
     * http://aigc.weijuyunke.cn/mobile/composite/avatarDel
     *
     * @param
     *            uid 用户id
     * @param
     *            avatar_id 形象id
     */
    public function avatarDel()
    {
        try {
            $uid = input('uid');
            $avatar_id = input('avatar_id');
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            $avatar = FigureCompositeAvatar::where([
                'uid' => $uid,
                'id' => $avatar_id
            ])->find();
            if (empty($avatar)) {
                return result(- 1, '形象不存在');
            }
            
            $avatar->delete();
            
            return result(0, '删除成功');
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 视频生成
     * http://aigc.weijuyunke.cn/mobile/composite/generate
     *
     * @param
     *            uid 用户id
     * @param
     *            name 视频标题
     * @param
     *            image_id 形象id
     * @param
     *            sound_id 声音id
     * @param
     *            width 宽度
     * @param
     *            height 高度
     * @param
     *            combination json配置
     * @param
     *            caption_josn 字幕配置
     *            
     */
    public function generate()
    {
        try {
            
            $request = $this->request;
            $param = $request->param();
            validate(\app\mobile\validate\Composite::class)->check($param);
            
            $uid = $param['uid'];
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            if (empty($param['sound_id']))
                return result(- 1, 'sound_id不能为空');
            
            if (empty($param['image_id']))
                return result(- 1, 'image_id不能为空');
            
            $sound = FigureCompositeSound::where([
                'uid' => $uid,
                'id' => $param['sound_id']
            ])->find();
            if (empty($sound)) {
                return result(- 1, 'sound不存在');
            }
            
            $image = FigureAvatar::where([
                'uid' => $uid,
                'id' => $param['image_id']
            ])->find();
            if (empty($image)) {
                return result(- 1, 'image不存在');
            }
            
            $duration = ceil(getDuration(1, $sound['url']));
            
            if ($duration == 0) {
                return result(- 1, '音频错误');
            }
            
            $tally = (float) sysconfig('tally', 'composite_deduct');
            $minute  = ceil($duration /60);
            $money = (float) $tally * $minute;
            
            if (! $user['is_member']) {
                if ($user['balance'] < $money) {
                    return result(- 2, '余额不足，请充值');
                }
            } else {
                if ($user['second_infinite'] == 0 && $user['second'] < $minute *60 && $user['balance'] < $money) {
                    return result(- 2, '余额不足，请充值');
                }
            }
            $log_no = getPayNo('JS');
            $params = array(
                'uid' => $uid,
                'name' => $param['name'],
                'type' => 2,
                'anchor_type' => 1,
                'image_id' => $image['_id'],
                'sound_id' => $sound['_id'],
                'duration' => $duration,
                'log_no' => $log_no
            );
            
            if (! empty($param['width'])) {
                $params['width'] = $param['width'];
            }
            
            if (! empty($param['height'])) {
                $params['height'] = $param['height'];
            }
            
            if (! empty($param['combination'])) {
                $params['combination'] = $param['combination'];
            }
            
            if (! empty($param['caption_json'])) {
                $params['caption_json'] = $param['caption_json'];
            }

            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();

            } else {
                $apiService = new ApiService();
            }
            $result = $apiService->submitVideo($params);
            
            if (isset($result['code']) && $result['code'] == 1) {
                
                $video = new FigureVideo();
                $video->save($params);
                

                
                $video->save([
                    '_id' => $result['data']['id'],
                    'current_status' => 'init'
                ]);

                $FigureWayName  = new \app\admin\model\FigureWayName();
                $FigureWayNameInfo  = $FigureWayName
                    ->where(['id' =>3])
                    ->find();
                user_balance_used($uid, $log_no, 2, 10, $minute,$FigureWayNameInfo['reception'].'创作');
                
                return result(0, '生成成功');
            } else {
                return result(- 1, $result['msg']);
            }
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public function avatarStatus(){
        try {
            $uid = input('uid');
            $avatar_id = input('avatar_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }

            $avatar =  FigureCompositeAvatar::where([
                'uid' => $uid,
                'id' =>$avatar_id
            ])->find();

            if (empty($avatar)) {
                return result(- 1, '形象不存在');
            }

            $flag = 0;


            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();

            } else {
                $apiService = new ApiService();

            }
            $result = $apiService->CompositeAvatarDetail($avatar['_id']);

            if (isset($result['code']) && $result['code'] == 1) {

                if (isset($result['data'])) {

                    $avatar->save([
                        'current_status' => $result['data']['current_status']
                    ]);

                    if ($result['data']['current_status'] == 'completed') {
                        $flag = 1;
                    }
                }
            }

            return result(0, 'success', $flag);
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }
}